/**********************************************************************
 Name:  CalculateVisitRange,trigger
 Purpose: 在PDA上传新的店面拜访记录时，计算当前坐标与对应店面的标准坐标偏差距离                                                           
-------                                                             
======================================================
History                                                            
-------                                                            
VERSION  AUTHOR               DATE                 DETAIL                                
   1.0 -      huang xiaojiang      03/21/2010      Create          : 
***********************************************************************/

trigger CalculateVisitRange on In_Store_Visit__c (after insert) {

    //variables
   set<id> setAccountId=new set<id>();
   
    list<In_Store_Visit__c> lISV=[select id,name,OutletName_del__c,lat__c,lon__c,devRange__c from In_Store_Visit__c where id in:trigger.newMap.keyset()];
    for(In_Store_Visit__c i:lISV){
        setAccountId.add(i.OutletName_del__c);
    }
    
    
    map<id,Account> mapAccount=new  map<id,Account>((list<Account>)[select id,name,lat__c,lon__c from Account where id in:setAccountId]);
    
    //计算门店拜访与标准店面之间偏差
    integer R=6371000;//地球半径，单位米
    double PI=3.1415926;//圆周率
    Account oAcc=new Account();
    
    for(In_Store_Visit__c i:lISV){
      
        string strAccountId=i.OutletName_del__c;
        oAcc=mapAccount.get(strAccountId);
        
        if(oAcc!=null&&i.lat__c!=null&&i.lon__c!=null){
            if(oAcc.lat__c!=null&&oAcc.lon__c!=null){
                double Lat1=double.valueOf(i.lat__c);
                double Lat2=double.valueOf(oAcc.lat__c);
                double Lon1=double.valueOf(i.lon__c);
                double Lon2=double.valueOf(oAcc.lon__c);
                
                double dLat=(lat2-lat1)*PI/180;
                double dLon=(lon2-lon1)*PI/180;
              
                double a=Math.sin(dLat/2) * Math.sin(dLat/2) +
                    Math.cos(lat1 * PI / 180 ) * Math.cos(lat2 * PI / 180 ) * 
                    Math.sin(dLon/2) * Math.sin(dLon/2); 
                    
                double c=2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
                double dRange=R*c;
                
                //把距离赋值
                i.devRange__c=dRange;            
            }else{
                //拜访有坐标，门店没坐标
                i.devRange__c=0;    
            }
        }
       
    }
    
    //更新数据
    if(lISV.size()>0){
        update lISV;
    }
    
    
}